package elcom.control.inputter;

import java.util.ArrayList;

import elcom.model.common.Log;
import elcom.model.data.QueueIO;
import elcom.model.data.Student;
import elcom.model.data.TransferData;

public class Inputter extends Thread {
	private QueueIO<Student> queIn;
	private ArrayList<Student> lstStudent = null;
	private TransferData td = new TransferData();

	public Inputter(QueueIO<Student> queIn) {
		this.queIn = queIn;
	}

	@Override
	public void run() {
		while (true) {
			try {
				if (checkQue()) {
					getData();
					sendData();
				} else {
					synchronized (queIn) {
						queIn.wait(1000);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.logErr(e.toString());
			}
		}
	}

	private void getData() {
		lstStudent = td.getData(getRownum());
	}

	private boolean checkQue() {
		if (queIn.size() <= 10000) {
			return true;
		}
		return false;
	}

	private int getRownum() {
		int rownum = 0;
		int size = queIn.size();
		rownum = 10000 - size;
		if (rownum > 2000) {
			rownum = 0;
		}
		return rownum;
	}

	private void sendData() {
		synchronized (queIn) {
			for (int i = 0; i < lstStudent.size(); i++) {
				Student student = lstStudent.get(i);
				queIn.addLast(student);
			}
			td.updateData(lstStudent);
			lstStudent.clear();
		}
	}
}
